from django.db.models import Manager
from django.db.models import Sum, Count
from django.utils.translation import ugettext_lazy as _

CONTENT_TR = {'draft': 0, 'public': 1, 'hidden': 2, 'banned': 3}
CONTENT_STATUSES = []
for k, v in CONTENT_TR.items():
    CONTENT_STATUSES.append((v, _(k)))


class QuestionPrivateManager(Manager):
    """Returns published posts that are not in the future."""
    
    def get_query_set(self):
        """ Select scores for the object """
        from django.contrib.contenttypes.models import ContentType
        model_type = ContentType.objects.get_for_model(self.model)
        table_name = self.model._meta.db_table
        queryset = super(QuestionPrivateManager,self).get_query_set().extra(select={'score': 'SELECT SUM(vote) FROM votes WHERE content_type_id=%i AND object_id=%s.id' % (int(model_type.id), table_name)})
        queryset = queryset.extra(select={'answer_count': 'SELECT COUNT(*) FROM ask_answer WHERE question_id=%s.id' % (table_name)})
        queryset = queryset.extra(select={'is_solved': 'SELECT COUNT(*) FROM ask_answer WHERE question_id=%s.id AND is_accepted=TRUE' % (table_name)})
        return queryset

class QuestionPublicManager(QuestionPrivateManager):
    """Returns published posts that are not in the future."""
    use_for_related_fields = True
    
    def get_query_set(self):
        return super(QuestionPublicManager,self).get_query_set().filter(status=CONTENT_TR['public'])

class AnswerPrivateManager(Manager):
    """Returns published posts that are not in the future."""
    
    def get_query_set(self):
        """ Select scores for the object """
        from django.contrib.contenttypes.models import ContentType
        model_type = ContentType.objects.get_for_model(self.model)
        table_name = self.model._meta.db_table
        return super(AnswerPrivateManager,self).get_query_set().extra(select={'score': 'SELECT SUM(vote) FROM votes WHERE content_type_id=%i AND object_id=%s.id' % (int(model_type.id), table_name)})

class AnswerPublicManager(AnswerPrivateManager):
    """Returns published posts that are not in the future."""
    use_for_related_fields = True
    
    def get_query_set(self):
        return super(AnswerPublicManager,self).get_query_set().filter(status=CONTENT_TR['public'])
